﻿using System;
using System.Collections.Generic;
using System.Linq;
using InvestmentIntelligence.DbModel.Models;

namespace InvestmentIntelligence.Data.Repository.EFImplementation
{
    public class EntityRepository : IIPRepository<Entity>, IEntityRepository
    {
        private readonly UserRepository _userRepository = new UserRepository();

        public new int Add(Entity entity)
        {
            base.Add(entity);
            return entity.Id;
        }

        public void Remove(int entityId)
        {
            RunUnitOfWork(data =>
                                {
                                    var entity = data.Entities.Single(x => x.Id == entityId);
                                    foreach (var role in entity.Roles.ToList())
                                    {
                                        _userRepository.RemoveRole(role.Id);
                                    }
                                    data.Entities.Remove(entity);
                                    data.SaveChanges(); return default(Entity);
                                });
        }

        public Entity Get(int entityId)
        {
            return Get(v => v.Id == entityId);
        }

        public new void Update(Entity entity)
        {
            RunUnitOfWork(data =>
                             {
                                 var actualEntity = data.Entities.SingleOrDefault(x => x.Id == entity.Id);
                                 if (actualEntity == null)
                                 {
                                     throw new NullReferenceException("Entity no exist");
                                 }

                                 actualEntity.Name = entity.Name;
                                 data.SaveChanges(); return default(Entity);
                             });
        }

        public List<T> GetUserList<T>(Func<IQueryable<User>, IEnumerable<T>> f, int entityId)
        {
            return InternalGet(
                dc =>
                {
                    var entity = dc.Entities.SingleOrDefault(x => x.Id == entityId);
                    if (entity == null)
                    {
                        throw new NullReferenceException("Entity no exist");
                    }
                    var users = dc.User2Role.Where(x => x.Role.EntityId == entityId).Select(x => x.User);
                    return users;
                }, z => f(z).ToList());
        }

    }
}